package com.azt.front.servlet;

import com.azt.front.utils.Globals;
import com.azt.utils.CommonUtil;
import com.azt.utils.VerifyCodeUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName AuthImage
 * @Description 图片验证码生成servlet
 * @author Snowler
 * @Date 2016年7月28日 下午3:00:16
 * @version 1.0.0
 */
public class AuthImage extends HttpServlet implements Servlet {
	
	

	static final long serialVersionUID = 1L;  
	  
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer w = CommonUtil.safeToInt(request.getParameter("w"), 200);    //宽度
        Integer h = CommonUtil.safeToInt(request.getParameter("h"), 80);     //高度
        String session_name = request.getParameter("n");    //存到session中的key
        if(StringUtils.isBlank(session_name)) {
            session_name = Globals.VALIDATE_IMAGE;
        }
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
          
        //生成随机字串  
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);  
        //存入会话session  
        HttpSession session = request.getSession(true);  
        session.setAttribute(session_name, verifyCode.toLowerCase());
        //生成图片  
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
  
    }  
}
